<template>
    <BasicModal
      v-bind="$attrs"
      @register="registerModal"
      show-footer
      width="60%"
      @ok="handleSubmit"
    >
      <template #title>
        {{ isUpdate ? '编辑' : '新增' }}
      </template>
      <template #footer>
        <a-button @click="closeModal" :loading="btnLoading">取消</a-button>
        <a-button
          type="primary"
          @click="handleSubmit(false)"
          :loading="btnLoading"
          >保存</a-button
        >
      </template>
      <BasicForm @register="registerForm">
      </BasicForm>
    </BasicModal>
  </template>
  <script lang="ts" setup>
  import { ref } from 'vue';
  import { BasicModal, useModalInner } from '@/components/Modal';
  import { BasicForm, useForm } from '@/components/Form/index';
  import { useMessage } from '@/hooks/web/useMessage';
  import { useThrottleFn } from '@vueuse/core';
  import { defHttp } from '@/utils/http/axios';
  const emit = defineEmits(['success', 'register']);
  let isUpdate = ref(true);
  const btnLoading = ref(true);
  const { createMessage } = useMessage();
  const [
    registerForm,
    { resetFields, setFieldsValue, validate },
  ] = useForm({
    labelWidth: 150,
    baseColProps: { span: 24 },
    schemas: [
        {
          field: 'stationId',
          component: 'Input',
          label: '站点ID',
          show: false,
        },
        {
          field: 'id',
          component: 'Input',
          label: 'id',
          show: false,
        },
        {
        field: 'type',
        component: 'Input',
        label: 'type',
        show: false,
        },
        {
          field: 'name',
          component: 'Input',
          label: '名称',
          required: true,
        },
        {
          field: 'protocolType',
          component: 'Select',
          label: '通信协议',
          required: true,
          componentProps: {
            options: [
              { label: '万马本地', value: 0 },
              { label: '特来电互联互通', value: 1 },
              { label: '云快充', value: 10 },
            ]
          },
        },
        {
          field: 'operatorId',
          component: 'ApiSelect',
          label: '运营商',
          required: true,
          componentProps: {
            api: '/admin/main/operatorList',
            labelField: 'memo',
            valueField: 'id',
          }
        },
        {
          field: 'terminalTypeId',
          component: 'ApiSelect',
          label: '终端类型',
          required: true,
          componentProps: {
            api: '/admin/main/terminalTypeList',
            labelField: 'name',
            valueField: 'id',
            clearable: true,
          }
        },
        {
          field: 'chargeInterfaceId',
          component: 'ApiSelect',
          label: '充电接口',
          required: true,
          componentProps: {
            api: '/admin/main/chargeInterfaceList',
            labelField: 'name',
            valueField: 'id',
            clearable: true,
          },
        },
        {
          field: 'powerMin',
          component: 'InputNumber',
          label: '功率最小值',
          required: true,
        },
        {
          field: 'powerMax',
          component: 'InputNumber',
          label: '功率最大值',
        },
        {
          field: 'voltageMin',
          component: 'InputNumber',
          label: '电压最小值',
          required: true,
        },
        {
          field: 'voltageMax',
          component: 'InputNumber',
          label: '电压最大值',
        },
        {
          field: 'assistPowerType',
          component: 'Input',
          label: '辅源类型',
          required: true,
        },
        {
          field: 'canIndex',
          component: 'Input',
          label: '枪编号',
          required: true,
          componentProps: ({ formModel }) => ({
            onChange: (v) => {
              const { canIndex, controllerSn } = formModel;
              setTimeout(() => {
                if (canIndex && controllerSn) {
                  formModel.pileSn = `${formModel.controllerSn}${formModel.canIndex}` 
                } else {
                  formModel.pileSn = ''
                } 
              }, 500)           
            }
          }),
        },
        {
          field: 'controllerSn',
          component: 'Input',
          label: '设备编号',
          required: true,
          componentProps: ({ formModel }) => ({
            onChange: (v) => {
              const { canIndex, controllerSn } = formModel;
              setTimeout(() => {
                if (canIndex && controllerSn) {
                  formModel.pileSn = `${formModel.controllerSn}${formModel.canIndex}` 
                } else {
                  formModel.pileSn = ''
                } 
              }, 500)           
            }
          }),
        },
        {
          field: 'pileSn',
          component: 'Input',
          label: '桩编号',
          dynamicDisabled: true,
        }
    ],
    showActionButtonGroup: false,
  });
  const [registerModal, { closeModal, changeLoading }] =
  useModalInner(async (data) => {
      resetFields();
      changeLoading(true);
      btnLoading.value = true;
      isUpdate.value =!!data?.isUpdate;
      if (isUpdate.value) {
        const res = await defHttp.get({ url: `/admin/pile/yu/detail/${data.record.id}` });
        setFieldsValue({ ...res });
      } else {
        setFieldsValue({ stationId: data.record.stationId });
      }
      changeLoading(false);
      btnLoading.value = false;
    });
  const handleSubmit = useThrottleFn(doSubmit, 1000);
  async function doSubmit() {
    try {
      changeLoading(true);
      btnLoading.value = true;
      const values = await validate();
      if (isUpdate.value) {
        const res = await defHttp.post({ url: '/admin/pile/yu_edit', data: values });
        createMessage.success(res);
      } else {
        const res = await defHttp.post({ url: '/admin/pile/yu_add', data: values });
        createMessage.success(res);
      }
      emit('success');
      closeModal();
    } finally {
      btnLoading.value = false;
      changeLoading(false);
    }
  }
  </script>
  